package net.hands.ctx.element;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import net.hands.common.I18n;
import net.hands.common.StringUtils;
import net.hands.common.web.html.HtmlEncoder;

/**
 * 
 * 说明：抽象元素
 * 
 * @package net.simpleframework.common.web.html.element
 * @author shihb(shihaibin.sea@gmail.com, 13466609192)
 *         <p>
 *         http://code.google.com/p/simpleframework/
 *         </p>
 *         <p>
 *         http://www.simpleframework.net
 *         </p>
 * @update 2013-1-3 下午3:23:58
 */
@SuppressWarnings("unchecked")
public abstract class AbstractElement<T extends AbstractElement<T>> {
	/**
	 * html 标签的id属性
	 */
	private String id;

	private String text; // html 标签中内容

	private Map<String, Object> attributes; // 元素属性

	private String style;

	public String getId() {
		return id;
	}

	public T setId(String id) {
		this.id = id;
		return (T) this;
	}

	public String getText() {
		return text;
	}

	public T setText(final String text) {
		this.text = I18n.replaceI18n(text);
		return (T) this;
	}

	public T addAttribute(final String key, final Object val) {
		// if (BeanUtils.hasProperty(this, key)) {
		// throw BeanException.of($m("AbstractElement.0", key));
		// }
		// if (attributes == null) {
		// attributes = new KVMap();
		// }
		// attributes.put(key, val);
		return (T) this;
	}

	protected T attri(final StringBuilder sb, final String attri) {
		// final Object obj = BeanUtils.getProperty(this, attri);
		// if (obj != null) {
		// sb.append(" ").append(attri).append("=\"");
		// sb.append(HtmlEncoder.text(String.valueOf(obj))).append("\"");
		// }
		return (T) this;
	}

	protected void doAttri(final StringBuilder sb) {
		attri(sb, "id");
		if (attributes != null) {
			for (final Map.Entry<String, Object> e : attributes.entrySet()) {
				sb.append(" ").append(e.getKey()).append("=\"");
				sb.append(HtmlEncoder.text(String.valueOf(e.getValue())))
						.append("\"");
			}
		}
	}

	public String getStyle() {
		return style;
	}

	public T setStyle(final String style) {
		this.style = style;
		return (T) this;
	}

	public T addStyle(final String style) {
		final Set<String> set = toSet(getStyle());
		set.addAll(toSet(style));
		this.style = StringUtils.join(set, ";");
		return (T) this;
	}

	private static Set<String> toSet(final String style) {
		final Set<String> set = new LinkedHashSet<String>();
		if (StringUtils.hasText(style)) {
			set.addAll(Arrays.asList(StringUtils.split(style.replace(" ", "")
					.toLowerCase(), ";")));
		}
		return set;
	}

	@Override
	public String toString() {
		return getText();
	}
}
